package de.slothsoft.network;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;

import javax.swing.JButton;
import javax.swing.JPanel;

@SuppressWarnings("nls")
public class ClientPanel extends AbstractNetworkPanel {

	private static final long serialVersionUID = 1L;

	private Client client;

	@Override
	protected void createTopControls(JPanel parent) {
		parent.setLayout(new FlowLayout(FlowLayout.LEFT));

		final JButton connectButton = new JButton("Verbinden");
		parent.add(connectButton);

		final JButton disconnectButton = new JButton("Trennen");
		disconnectButton.setEnabled(false);
		parent.add(disconnectButton);

		connectButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				try {
					createConnection();
					connectButton.setEnabled(false);
					disconnectButton.setEnabled(true);
				} catch (Exception e) {
					e.printStackTrace(getOutputStream());
					connectButton.setEnabled(true);
					disconnectButton.setEnabled(false);
				}
			}
		});

		disconnectButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				killConnection();
				connectButton.setEnabled(true);
				disconnectButton.setEnabled(false);
			}
		});
	}

	protected void createConnection() throws UnknownHostException, IOException {
		this.client = Client.createClient(InetAddress.getLocalHost(), NetworkTest.PORT);
		getOutputStream().println("Verbinde mit Server.");
		getOutputStream().println("Sende 'Hallo Welt!'");
		this.client.getOutputStream().writeObject("Hallo Welt!");
		this.client.addClientListener(new ClientListener() {

			@Override
			public void receivedObject(ClientEvent event) {
				getOutputStream().println("Nachricht erhalten: " + event.getIncomingObject());
			}

			@Override
			public void disconnected(ClientEvent event) {
				getOutputStream().println("Verbindung getrennt.");
			}
		});
		this.client.start();
	}

	protected void killConnection() {
		if (this.client != null) {
			try {
				this.client.disconnect();
			} catch (NetworkException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}
